package com.lbs.jiepiaisi.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.utils.SpatialRelationUtil;
import com.amap.api.maps.utils.overlay.SmoothMoveMarker;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.HistoryTraceBean;
import com.xw.repo.BubbleSeekBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 *
 * 时间：2017/9/1 14:30
 * 作用：历史轨迹类
 */
public class HistoryTracePlayActivity extends BaseActivity {
    private ArrayList<LatLng> latlngList_path = new ArrayList<LatLng>();//进度值存放的坐标数据
    private List<LatLng> latLngs = null;//经纬度集合
    //private UiSettings mUiSettings;//比例尺
    private MapView mapView;//地图
    private AMap aMap;
    private SmoothMoveMarker smoothMoveMarker;//平滑移动点Marker
    private BubbleSeekBar seekSpeed, seekSchedule;
    private ImageView play, pause;
    private static int  progressNum=0;//正常进度点
    private static int listTime;//现在所需时长
    //当前设备的设备编号
    private String eqNo;
    //当前设备的车主姓名
    private String ownerName;
    //实体类对象
    private HistoryTraceBean historyTraceBean;
    // 初始化定时器
    private Timer timer = new Timer();
    private TimerTask timerTask;
    //判断是否在运行
    private boolean isRun = false;
    //最大车速
    private float maxV = 0;
    //最小车速
    private float minV = 0;
    //当前运行的position
    private int pos = 0;
    //覆盖层marker
    private Marker screenMarker;
    private View v;
    //marker遮盖层
    private LinearLayout infoWindowLayout;
    private TextView title;
    private TextView snippet;
    private TextView mTvCarName, mTvDevice, mTvStatus, mTvTime, mTvOrientation, mTvType, mTvSpeed;

//    Handler handler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                //播放完成
//                case 1 :
//                    //播放完成后显示设置
//                    findViewById(R.id.play).setVisibility(View.VISIBLE);
//                    findViewById(R.id.pause).setVisibility(View.GONE);
//                    break;
//            }
//        }
//    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_trace_play);
        titleView.setText("轨迹回放");
        mapView = (MapView)findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写

        getExras();
        initView();
        initEvent();
        initData();
        //findView();
        //setListener();
    }

    private void initData() {
        setLine();
    }

    /**
     * 画线
     */
    public void setLine() {
        //添加起始显示信息
        addMarkersOnMap(historyTraceBean.getResult());
        addLine();
        addMarkerInScreenCenter();
        if(historyTraceBean.getResult().get(0).getSpeed().equals("") ||
                historyTraceBean.getResult().get(0).getSpeed() == null){
            minV = 0;
        }else {
            minV = Float.valueOf(historyTraceBean.getResult().get(0).getSpeed());
        }
        for(int i = 0; i< historyTraceBean.getResult().size(); i++){
            float v = 0;
            if(historyTraceBean.getResult().get(0).getSpeed().equals("") ||
                    historyTraceBean.getResult().get(0).getSpeed() == null){
                v = 0;
            }else {
                v = Float.valueOf(historyTraceBean.getResult().get(0).getSpeed());
            }
            if(v > maxV){
                maxV = v;
            }
            if(v < minV){
                minV = v;
            }
        }
        seekSpeed.getConfigBuilder()
                .hideBubble()
                .build();

        seekSchedule.getConfigBuilder()
                .min(0)
                .max(historyTraceBean.getResult().size())
                .hideBubble()
                .build();
    }

    /**
     * 添加线
     */
    private void addLine() {
        List<LatLng> latLngs = new ArrayList<LatLng>();
        for(int i = 0; i< historyTraceBean.getResult().size(); i++){
            latLngs.add(new LatLng(historyTraceBean.getResult().get(i).getGdLat(),
                    historyTraceBean.getResult().get(i).getGdLng()));
        }
        Polyline polyline = aMap.addPolyline(new PolylineOptions().setCustomTexture(BitmapDescriptorFactory.fromResource(R.mipmap.custtexture))
                .addAll(latLngs).width(15));
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
                historyTraceBean.getResult().get(0).getGdLng()), 17));
    }

    /**
     * 初始化定时器
     */
    private void initTime() {
        play();
        timer.schedule(timerTask, 100, 600);
    }

    private void play() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if(isRun){
                    pos ++;
                    if(pos == historyTraceBean.getResult().size()){
                        isRun = false;
                        pos = 0;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                play.setImageResource(R.mipmap.play);
                            }
                        });
                        //stopTimer();
                        return;
                    }
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
                            historyTraceBean.getResult().get(pos).getGdLng())));
//                    screenMarker.setPositionNotUpdate(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
//                            historyTraceBean.getResult().get(pos).getGdLng()));
                    screenMarker.setPositionNotUpdate(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
                            historyTraceBean.getResult().get(pos).getGdLng()));
                    //aMap.runOnDrawFrame();
                    //速度
                    final String speed= historyTraceBean.getResult().get(pos).getSpeed();
                    //时间
                    final String positionTime= historyTraceBean.getResult().get(pos).getPositionTime();
                    //角度
                    final float rotate = historyTraceBean.getResult().get(pos).getRotate();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            getInfoView();
                            if(mTvCarName == null) {
                                return;
                            }
                            seekSchedule.setProgress(pos);
                            screenMarker.setRotateAngle(360 - rotate);
                            mTvCarName.setText(ownerName + "");
                            mTvDevice.setText(eqNo + "");
                            mTvTime.setText(positionTime + "");
                            mTvOrientation.setText(getDir(rotate));
                            mTvType.setText(historyTraceBean.getResult().get(pos).getPostType() + "");
                            mTvSpeed.setText(speed + "km/h");
                            //状态
//                            if(historyTraceBean.getResult().get(pos).getSatatus().equals("")){
//                                mTvStatus.setText("");
//                            }else {
//                                final String satatus = historyTraceBean.getResult().get(pos).getSatatus();
//                                mTvStatus.setText(satatus);
//                            }
                        }
                    });
                }
            }
        };
    }

    private void initView() {
        /**
         * 初始化AMap对象
         */
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        seekSpeed = findViewById(R.id.seek_speed);
        seekSchedule = findViewById(R.id.seek_schedule);
        play = findViewById(R.id.play);
        pause = findViewById(R.id.pause);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
        if(timer == null || timerTask == null){
            timer = new Timer();
            initTime();
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    private void getExras() {
        //取出sp存储的设备编号和车主姓名
        Intent intent = getIntent();
        eqNo = intent.getStringExtra("eqNo");
        ownerName = intent.getStringExtra("ownerName");
        historyTraceBean = (HistoryTraceBean)intent.getSerializableExtra("historyTraceBean");
        //初始化定时器
        initTime();
    }
//    private void findView() {
//        if (aMap == null) {
//            aMap = mapView.getMap();
//            mUiSettings = aMap.getUiSettings();
//            mUiSettings.setScaleControlsEnabled(true);
//            //不能旋转
//            mUiSettings.setRotateGesturesEnabled(false);
//            //不能倾斜
//            mUiSettings.setTiltGesturesEnabled(false);
//        }
////        seekbar_sudu= (SeekBar) findViewById(R.id.seekbar_sudu);
////        seekbar_jindu= (SeekBar) findViewById(R.id.seekbar_jindu);
//        /**
//         * 设置地图展示
//         */
//        setMap();
//    }

//    private void setListener() {
//        /**
//         * 开始或暂停
//         */
//        findViewById(R.id.re_start_stop).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if(flag==0) {
//                    //点击开始
//                    flag=1;
//                    findViewById(R.id.play).setVisibility(View.GONE);
//                    findViewById(R.id.pause).setVisibility(View.VISIBLE);
//                    //判断当前进度是否走到最后
////                    if(seekbar_jindu.getProgress()== historyTraceBean.getResult().size()-1){
////                        progressNum=0;
////                        seekbar_jindu.setProgress(progressNum);
////                        latlngList_path.clear();
////                        for(int i = 0; i< historyTraceBean.getResult().size(); i++){
////                            LatLng newLatlng  = new LatLng(historyTraceBean.getResult().get(i).getGdLat(), historyTraceBean.getResult().get(i).getGdLng());
////                            latlngList_path.add(i,newLatlng);
////                        }
////                        //在起点设置移动点
////                        moveSmoothMoveMarker(latlngList_path);
////                        smoothMoveMarker.setTotalDuration(10);//重置时间（单位秒）
////                        smoothMoveMarker.startSmoothMove();
////                    }else{
////                        smoothMoveMarker.startSmoothMove();
////                    }
//                }else{
//                    flag=0;
//                    findViewById(R.id.play).setVisibility(View.VISIBLE);
//                    findViewById(R.id.pause).setVisibility(View.GONE);
//                    //暂停移动点
//                    smoothMoveMarker.stopMove();
//                }
//            }
//        });
//        /**
//         * 速度控制条
//         */
////        seekbar_sudu.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
////            @Override
////            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
////                Log.e("speed00000","seekbar_sudu00000");
////                if(progress==5){
////                    smoothMoveMarker.setTotalDuration(listTime);
////                }if(progress==4){
////                    smoothMoveMarker.setTotalDuration(listTime+12);
////                }if(progress==3){
////                    smoothMoveMarker.setTotalDuration(listTime+18);
////                }if(progress==2){
////                    smoothMoveMarker.setTotalDuration(listTime+24);
////                }if(progress==1){
////                    smoothMoveMarker.setTotalDuration(listTime+30);
////                }
////            }
////            @Override
////            public void onStartTrackingTouch(SeekBar seekBar) {}
////            @Override
////            public void onStopTrackingTouch(SeekBar seekBar) {}
////        });
//        /**
//         * 进度控制条
//         */
////        seekbar_jindu.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
////            @Override
////            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
////                Log.e("speed00000","seekbar_sudu11111");
////                if (fromUser){
////                    latlngList_path.clear();
////                    for(int i=progress;i<latLngs.size();i++){//注意：i从0开始的，所以小于latLngs.size
////                        latlngList_path.add(latLngs.get(i));
////                    }
////                    //在起点设置移动点
////                    moveSmoothMoveMarker(latlngList_path);
////                    progressNum=progress;
////                    //所需剩余时间
////                    double  overTime=(double) time/(historyTraceBean.getResult().size()-1)*progressNum;
////                    listTime= (int) overTime;
////                    listTime=time-listTime;//所需的剩余时间
////                    smoothMoveMarker.setTotalDuration(listTime);//单位秒
////                    //在开始的过程中拖动进度条，拖动完成后自动开始
////                    int resultView;//返回值为0，visible；返回值为4，invisible；返回值为8，gone
////                    resultView= findViewById(R.id.play).getVisibility();
////                    if(resultView==8){
////                        smoothMoveMarker.startSmoothMove();
////                    }
////                    setMoveFlag();
////                }
////            }
////            @Override
////            public void onStartTrackingTouch(SeekBar seekBar) {
////
////            }
////
////            @Override
////            public void onStopTrackingTouch(SeekBar seekBar) {
////
////            }
////        });
//    }

    /**
     * 设置地图展示
     */
    public void setMap() {
        aMap.clear();
        //设置进度条
        progressNum=0;
        //设置进度条的进度值（正常进度值为0-100）
        //seekbar_jindu.setMax(historyTraceBean.getResult().size()-1);
        //设置速度条的速度值
        //seekbar_sudu.setMax(5);
        //seekbar_sudu.setProgress(5);
        //设置加载时间
        listTime=10;
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        aMap.setMyLocationStyle(myLocationStyle);
        //画线
        markPointsOnMap(historyTraceBean.getResult());
        //添加起始显示信息
        addMarkersOnMap(historyTraceBean.getResult());
        //设置移动点
        //注：之所以转换类型，是为了能取到重播起点LatLng
        latlngList_path.clear();
        for(int i = 0; i< historyTraceBean.getResult().size(); i++){
            LatLng newLatlng  = new LatLng(historyTraceBean.getResult().get(i).getGdLat(), historyTraceBean.getResult().get(i).getGdLng());
            latlngList_path.add(i,newLatlng);
        }
        //在起点设置移动点
        moveSmoothMoveMarker(latlngList_path);
    }

    /**
     * 画线
     */
    private void markPointsOnMap(final List<HistoryTraceBean.Result> getResult) {
        aMap.clear();
        latLngs = new ArrayList<LatLng>();
        // 获取轨迹坐标点
        LatLngBounds.Builder var1 = LatLngBounds.builder();
        for(int i=0;i<getResult.size();i++){
            LatLng newLatlng = new LatLng(getResult.get(i).getGdLat(),getResult.get(i).getGdLng());
            latLngs.add(newLatlng);
            var1.include(newLatlng);
        }
        //画线
        aMap.addPolyline(new PolylineOptions().setCustomTexture(BitmapDescriptorFactory.fromResource(R.mipmap.custtexture))
                .addAll(latLngs).width(15));
        //移动到当前线
        //aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(var1.build(),(WindowSizeUtil.getWidth(mContext)) / 7));
        //aMap.setPointToCenter(WindowSizeUtil.getWidth(mContext) / 2, WindowSizeUtil.getHeight(mContext) / 2);
//        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
//                historyTraceBean.getResult().get(0).getGdLng()), 17));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
                historyTraceBean.getResult().get(0).getGdLng())));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

    }

    /**
     * 添加起始显示信息
     */
    private void addMarkersOnMap(List<HistoryTraceBean.Result> getResult){
        //设置起点显示信息
        View viewStart = View.inflate(mContext, R.layout.layout_marker_line, null);
        viewStart.findViewById(R.id.iv_marker).setBackgroundResource(R.mipmap.icon_start);
        //设置起点的时间信息
        ((TextView) viewStart.findViewById(R.id.tv_time_data)).setVisibility(View.GONE);
        ((TextView) viewStart.findViewById(R.id.tv_time_hour)).setVisibility(View.GONE);
        Bitmap bitmapStart = convertViewToBitmap(viewStart);
        LatLng startLatLng = new LatLng(getResult.get(0).getGdLat(),getResult.get(0).getGdLng());
        MarkerOptions markerStart = new MarkerOptions().icon(BitmapDescriptorFactory
                .fromBitmap(bitmapStart))
                .alpha(0.6f)
                .position(startLatLng).anchor(0.5f, 0.5f)
                .draggable(true);
        aMap.addMarker(markerStart);
        //设置终点显示信息
        View viewEnd = View.inflate(mContext, R.layout.layout_marker_line, null);
        viewEnd.findViewById(R.id.iv_marker).setBackgroundResource(R.mipmap.icon_end);
        //设置终点的时间信息
        ((TextView) viewEnd.findViewById(R.id.tv_time_data)).setVisibility(View.GONE);
        ((TextView) viewEnd.findViewById(R.id.tv_time_hour)).setVisibility(View.GONE);
        Bitmap bitmapEnd = convertViewToBitmap(viewEnd);
        LatLng endLatLng = new LatLng(getResult.get(getResult.size()-1).getGdLat(),getResult.get(getResult.size()-1).getGdLng());
        MarkerOptions markerEnd = new MarkerOptions().icon(BitmapDescriptorFactory
                .fromBitmap(bitmapEnd))
                .alpha(0.6f)
                .position(endLatLng).anchor(0.5f, 0.5f)
                .draggable(true);
        aMap.addMarker(markerEnd);
    }

    //view 转bitmap
    public static Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }

    /**
     * 在起点设置移动点
     */
    private void moveSmoothMoveMarker(ArrayList<LatLng> list) {
        if(smoothMoveMarker!=null){
            smoothMoveMarker.destroy();
        }
        /**
         * 注意：
         * list.size=25
         * list.get(0)为第一个
         * lsit.get(24)为最后一个
         */
        //重播起点
        LatLng replayGeoPoint = list.get(0);
        //设置平滑移动点的相关属性
        //按照指定的经纬度数据和时间，平滑移动
        smoothMoveMarker = new SmoothMoveMarker(aMap);
        //设置移动Marker的图标
        smoothMoveMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.mipmap.direct));
        //取轨迹点的第一个点,作为平滑移动的启动
        LatLng drivePoint = replayGeoPoint;
        //SpatialRelationUtil---计算点到线最短距离工具类
        Pair<Integer, LatLng> pair = SpatialRelationUtil.calShortestDistancePoint(list, drivePoint);
        list.set(pair.first, drivePoint);
        List<LatLng> subList = list.subList(pair.first, list.size());
        //在起点设置Mark
        smoothMoveMarker.setPoints(subList);
        //设置加载时间
        smoothMoveMarker.setTotalDuration(listTime);//单位秒

        //开启回调
        smoothMoveMarker.setMoveListener(new SmoothMoveMarker.MoveListener(){
            @Override
            public void move(double distance) {
                setMoveFlag();
                if (progressNum == 1) {
                    if ((int) distance > 1500000) {
                        smoothMoveMarker.setTotalDuration(500);//设置平滑移动的总时间
                    }
                    if ((int) distance < 1500000 && (int) distance > 100000) {
                        smoothMoveMarker.setTotalDuration(400);//设置平滑移动的总时间
                    }
                    if ((int) distance < 100000 && (int) distance > 50000) {
                        smoothMoveMarker.setTotalDuration(250);//设置平滑移动的总时间
                    }
                    if ((int) distance < 50000 && (int) distance > 10000) {
                        smoothMoveMarker.setTotalDuration(150);//设置平滑移动的总时间
                    }
                    if ((int) distance < 10000) {
                        smoothMoveMarker.setTotalDuration(50);//设置平滑移动的总时间
                    }
                } else {
                    //正常回放速度
                    if ((int) distance > 1500000) {
                        smoothMoveMarker.setTotalDuration(1000);//设置平滑移动的总时间
                    }
                    if ((int) distance < 1500000 && (int) distance > 100000) {
                        smoothMoveMarker.setTotalDuration(800);//设置平滑移动的总时间
                    }
                    if ((int) distance < 100000 && (int) distance > 50000) {
                        smoothMoveMarker.setTotalDuration(500);//设置平滑移动的总时间
                    }
                    if ((int) distance < 50000 && (int) distance > 10000) {
                        smoothMoveMarker.setTotalDuration(300);//设置平滑移动的总时间
                    }
                    if ((int) distance < 10000) {
                        smoothMoveMarker.setTotalDuration(100);//设置平滑移动的总时间
                    }
                }
            }
        });
    }
    private void setMoveFlag(){
        //速度
        final String speed= historyTraceBean.getResult().get(progressNum).getSpeed();
        //时间
        final String positionTime= historyTraceBean.getResult().get(progressNum).getPositionTime();
        //角度
        final float rotate = historyTraceBean.getResult().get(progressNum).getRotate();
        /**
         * 设置信息弹窗
         */
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        //smoothMoveMarker.getMarker()
        smoothMoveMarker.getMarker().showInfoWindow();
        smoothMoveMarker.getMarker().setRotateAngle((-rotate));
        LatLng position= smoothMoveMarker.getPosition();
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(position));
        //弹窗设置
        runOnUiThread(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
//                LatLng position= smoothMoveMarker.getPosition();
//                aMap.moveCamera(CameraUpdateFactory.changeLatLng(position));
                if (infoWindowLayout != null && title != null) {
                    if(progressNum < historyTraceBean.getResult().size() ){
                        title.setText("  "+"车主："+ownerName+"  "
                                +"\n"+"  "+"设备号："+eqNo+"  "
                                +"\n"+"  "+"定位时间:"+positionTime+"  "
                                +"\n"+"  "+"定位方向:"+getDir(rotate)+"  "
                                +"\n"+"  "+"定位方式:"+ historyTraceBean.getResult().get(progressNum).getPostType()+"  "
                                +"\n"+"  "+"当前速度:"+speed+"km/h"+"  "
                        );
                    }

                }
            }
        });
//        //设置地图缩放比例
//        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
//        smoothMoveMarker.startSmoothMove();
//        smoothMoveMarker.getMarker().setVisible(true);
        //进度设置
        //seekbar_jindu.setProgress(progressNum);
        progressNum++;
//        if(seekbar_jindu.getProgress()== historyTraceBean.getResult().size()-1) {
//            handler.sendMessage(Message.obtain(handler, 1));
//        }
    }

    //信息弹窗adapter
    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter(){
        @Override
        public View getInfoWindow(Marker marker) {

            return getInfoView();
        }

        @Override
        public View getInfoContents(Marker marker) {

            return null;

        }
    };


    private View getInfoWindowView(Marker marker) {
        if (infoWindowLayout == null) {
            infoWindowLayout = new LinearLayout(this);
            infoWindowLayout.setOrientation(LinearLayout.VERTICAL);
            title = new TextView(this);
            snippet = new TextView(this);
            title.setTextColor(Color.BLACK);
            snippet.setTextColor(Color.BLACK);
            infoWindowLayout.setBackgroundResource(R.mipmap.infowindow_bg);
            infoWindowLayout.setAlpha(0.6f);
            infoWindowLayout.addView(title);
        }

        return infoWindowLayout;
    }

    private View getInfoView() {
        if(v == null){
            final View view = LayoutInflater.from(mContext).inflate(R.layout.layout_marker_infowindow_history, null);
            mTvCarName = view.findViewById(R.id.tv_card_name);
            mTvDevice = view.findViewById(R.id.tv_device);
            mTvStatus = view.findViewById(R.id.tv_status);
            mTvTime = view.findViewById(R.id.tv_time);
            mTvOrientation = view.findViewById(R.id.tv_orientation);
            mTvType = view.findViewById(R.id.tv_type);
            mTvSpeed = view.findViewById(R.id.tv_speed);
            v = view;
            return view;
        }else {
            return v;
        }
    }



    public String getDir(float dir){
        if(dir == 0 || dir == 360){
            return "正北";
        }
        if(dir > 0  && dir < 90){
            return "东北";
        }
        if(dir == 90){
            return "正东";
        }
        if(dir > 90  && dir < 180){
            return "东南";
        }
        if(dir == 180){
            return "正南";
        }
        if(dir > 180  && dir < 270){
            return "西南";
        }
        if(dir == 270){
            return "正西";
        }
        if(dir > 270  && dir < 360){
            return "西北";
        }
        return "";
    }

    private void initEvent() {
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isRun){
                    isRun = false;
                    play.setImageResource(R.mipmap.play);
                }else {
                    isRun = true;
                    play.setImageResource(R.mipmap.pause);
                }
            }
        });

        //调节速度
        seekSpeed.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {}

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {
                timer.cancel();
                timer = null;
                timerTask.cancel();
                timerTask = null;
                if(timer == null){
                    timer = new Timer();
                }
                if(timerTask == null){
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            if(isRun){
                                pos ++;
                                if(pos == historyTraceBean.getResult().size()){
                                    isRun = false;
                                    pos = 0;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            play.setImageResource(R.mipmap.play);
                                        }
                                    });
                                    //stopTimer();
                                    return;
                                }
                                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
                                        historyTraceBean.getResult().get(pos).getGdLng())));
                                screenMarker.setPositionNotUpdate(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
                                        historyTraceBean.getResult().get(pos).getGdLng()));

//                            screenMarker.setPosition(new LatLng(historyTraceBean.getResult().get(pos).getGdLat(),
//                            historyTraceBean.getResult().get(pos).getGdLng()));
                                //aMap.runOnDrawFrame();
                                //速度
                                final String speed= historyTraceBean.getResult().get(pos).getSpeed();
                                //时间
                                final String positionTime= historyTraceBean.getResult().get(pos).getPositionTime();
                                //角度
                                final float rotate = historyTraceBean.getResult().get(pos).getRotate();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        getInfoView();
                                        screenMarker.setRotateAngle(360 - rotate);
                                        seekSchedule.setProgress(pos);
                                        mTvCarName.setText(ownerName + "");
                                        mTvDevice.setText(eqNo + "");
                                        mTvTime.setText(positionTime + "");
                                        mTvOrientation.setText(getDir(rotate));
                                        mTvType.setText(historyTraceBean.getResult().get(pos).getPostType() + "");
                                        mTvSpeed.setText(speed + "km/h");
                                        //状态
//                                        if(historyTraceBean.getResult().get(pos).getSatatus().equals("")){
//                                            mTvStatus.setText("");
//                                        }else {
//                                            final String satatus = historyTraceBean.getResult().get(pos).getSatatus();
//                                            mTvStatus.setText(satatus);
//                                        }
                                    }
                                });
                            }
                        }
                    };
                }
                timer.schedule(timerTask, 1, 1000 - progress);
            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }
        });

        //调整进度
        seekSchedule.setOnProgressChangedListener(new BubbleSeekBar.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {
                if(progress > historyTraceBean.getResult().size() - 1){
                    isRun = false;
                    pos = 0;
                    play.setImageResource(R.mipmap.play);
                    return;
                }

                /*==========================暂时注释==========================*/
                aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(historyTraceBean.getResult().get(progress).getGdLat(),
                        historyTraceBean.getResult().get(progress).getGdLng())));
                screenMarker.setPositionNotUpdate(new LatLng(historyTraceBean.getResult().get(progress).getGdLat(),
                        historyTraceBean.getResult().get(progress).getGdLng()));
                /*==========================暂时注释==========================*/

                /*==========================测试代码==========================*/
//                Point screenPosition = aMap.getProjection().toScreenLocation(new LatLng(historyTraceBean.getResult().get(progress).getGdLat(),
//                        historyTraceBean.getResult().get(progress).getGdLng()));
//                screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
//                LatLng latLng = aMap.getCameraPosition().target;
//                Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
//                aMap.setPointToCenter(screenPosition.x, screenPosition.y);
                /*==========================测试代码==========================*/



                pos = progress;
                if(!isRun){
                    //速度
                    final String speed= historyTraceBean.getResult().get(progress).getSpeed();
                    //时间
                    final String positionTime= historyTraceBean.getResult().get(progress).getPositionTime();
                    //角度
                    final float rotate = historyTraceBean.getResult().get(progress).getRotate();
                    getInfoView();
                    screenMarker.setRotateAngle(360 - rotate);
                    mTvCarName.setText(ownerName + "");
                    mTvDevice.setText(eqNo + "");
                    mTvTime.setText(positionTime + "");
                    mTvOrientation.setText(getDir(rotate));
                    mTvType.setText(historyTraceBean.getResult().get(progress).getPostType() + "");
                    mTvSpeed.setText(speed + "km/h");
                    //状态
//                    if(historyTraceBean.getResult().get(pos).getSatatus().equals("")){
//                        mTvStatus.setText("");
//                    }else {
//                        final String satatus = historyTraceBean.getResult().get(pos).getSatatus();
//                        mTvStatus.setText(satatus);
//                    }
                }
            }

            @Override
            public void getProgressOnActionUp(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat) {

            }

            @Override
            public void getProgressOnFinally(BubbleSeekBar bubbleSeekBar, int progress, float progressFloat, boolean fromUser) {

            }
        });
    }


    /**
     * 在地图上加遮盖
     */
    private void addMarkerInScreenCenter() {
        if (screenMarker == null) {
            screenMarker = aMap.addMarker(new MarkerOptions()
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.direct)).draggable(false));
        }
        screenMarker.setAnchor(0.5f, 0.5f);
        screenMarker.setToTop();
        /*==========================暂时注释==========================*/
//        LatLng latLng = aMap.getCameraPosition().target;
//        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
//        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        screenMarker.setPosition(new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
                historyTraceBean.getResult().get(0).getGdLng()));
        /*==========================暂时注释==========================*/


//        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
//        screenMarker.setPosition(new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
//                historyTraceBean.getResult().get(0).getGdLng()));



        /*==========================测试代码==========================*/
//        LatLng latLng = aMap.getCameraPosition().target;
//        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
//        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
//        LatLng latLng = new LatLng(historyTraceBean.getResult().get(0).getGdLat(),
//                historyTraceBean.getResult().get(0).getGdLng());
//        Projection projection = aMap.getProjection();
//        Point screenPosition = projection.toScreenLocation(latLng);
//        int x = screenPosition.x;
//        int y = screenPosition.y;
//        com.lidroid.xutils.util.LogUtils.i("x================" + x);
//        screenMarker.setPosition(latLng);
        /*==========================测试代码==========================*/


        screenMarker.setClickable(false);
        /**
         * 设置信息弹窗
         */
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        screenMarker.showInfoWindow();
        screenMarker.setToTop();
    }

    // 停止定时器
    private void stopTimer(){
        if(timer != null){
            timer.cancel();
            // 一定设置为null，否则定时器不会被回收
            timer = null;
            timerTask.cancel();
            timerTask = null;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTimer();
    }
}
